﻿using System;
using System.IO;
using System.Net;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Web.Services;
using System.DirectoryServices;

//////////////////////////////////////////////////////////////////////////
//Default.aspx.cs                                                       //
//Last Edited: 26 Apr 2012                                              //
//                                                                      //
//The default page for advisees. Displays schedules in list view (LV)   //
//  or graphical view (GV).                                             //
//////////////////////////////////////////////////////////////////////////
public partial class Advisee_index : System.Web.UI.Page
{
    //////////////////////
    //Instance Variables//
    //////////////////////
    List<Course> courseList = new List<Course>(); //list of courses in schedule
    List<Elective> electiveList = new List<Elective>(); //list of electives in schedule

    //////////////////
    //Page Functions//
    //////////////////

    /// <summary>
    /// Page_Load()
    /// 
    /// Initializes the page.
    /// </summary>
    /// <param name="sender">object sender (unused, required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void Page_Load(object sender, EventArgs e)
    {
        //Get the ID and start date from Active Directory
        String adviseeID = SharedFunctions.getAdviseeID(Request);
        String startDate = SharedFunctions.getAdviseeStartDate(adviseeID);
        String startYear = startDate.Substring(startDate.IndexOf(' ')+1);
        int intStartYear = 0;
        if(!startDate.Equals("Uninitialized"))
            intStartYear = Convert.ToInt32(startYear);

        //If schedule is uninitialized
        if(!SharedFunctions.isInitialized(adviseeID))
        {
            //Set state of web controls for Uninitialized View
            HeaderText.Text = "Initialize Schedule";
            setUninitView(true);
            setGraphicalView(false);
            setListView(false);
        }
        else //Schedule is initialized
        {
            //Set Session Variables
            Session["Advisee_adviseeID"] = adviseeID;
            if (!IsPostBack)
            {
                //Set this only on the initial page load
                Session["Advisee_yearGV"] = startYear; //Current year being viewed in semester region 1 for GV
                //Insert student's transcript from banner into internal DB
                StoredProcedures.fetchAdviseeTranscript(adviseeID, adviseeID);
            }

            //If Graphical View is selected
            if (ViewRadio.SelectedIndex == 0) //i.e. The first item in the ViewRadio is selected
            {
                //Initialize all graphical view controls and JavaScript
                initializeJavaScript();
                //Set state of web controls for Graphical View
                setUninitView(false);
                setGraphicalView(true);
                setListView(false);
            }
            else //List View is selected
            {
                //Populate the MoveYearList with 10 years after the start year
                if (MoveYearList.Items.Count == 0)
                {
                    //Insert Transfer Credits
                    MoveYearList.Items.Add(new System.Web.UI.WebControls.ListItem("Transfer Credits"));
                    for (int i = intStartYear; i < intStartYear + 10; i++)
                    {
                        MoveYearList.Items.Add(new System.Web.UI.WebControls.ListItem("" + i));
                    }
                }
                //Create the ListViewTable
                generateListViewTable();
                //Set state of web controls for List View
                HeaderText.Text = "List View";
                setUninitView(false);
                setGraphicalView(false);
                setListView(true);
            }
        }
    } //end Page_Load()

    /// <summary>
    /// ChangeDisplayedSemester()
    /// 
    /// Updates all the semester lists on the page to reflect the appropriate semester to display (depending on start date)
    /// </summary>
    /// <param name="sender">object sender (unused, required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void ChangeDisplayedSemester(object sender, EventArgs e)
    {
        if (Session["Advisee_adviseeID"] == null || MoveYearList.SelectedItem == null)
            return;
        String startYear = SharedFunctions.getAdviseeStartYear(Session["Advisee_adviseeID"].ToString());
        String startSemester = SharedFunctions.getAdviseeStartSemester(Session["Advisee_adviseeID"].ToString());
        if (startYear.Equals("Uninitialized"))
            return;
        int intStartYear = Convert.ToInt32(startYear);
        int moveYear = 0;
        if (MoveYearList.SelectedItem.Text.Equals("Transfer Credits"))
        {
            if (startSemester.Equals("Spring"))
                moveYear = intStartYear - 1;
            else
                moveYear = intStartYear;
            MoveSemesterList.Items.Clear();
            MoveSemesterList.Items.Add(new System.Web.UI.WebControls.ListItem("----"));
            return;
        }
        else
            moveYear = Convert.ToInt32(MoveYearList.SelectedItem.Text);
        
        int selectedSemesterIndex = MoveSemesterList.SelectedIndex;
        MoveSemesterList.Items.Clear();
        if (moveYear == intStartYear)
        {
            //String startSemester = SharedFunctions.getAdviseeStartSemester(Session["Advisee_adviseeID"].ToString());
            
            if (startSemester.Equals("Fall"))
            {
                MoveSemesterList.Items.Add(new System.Web.UI.WebControls.ListItem("Fall"));
            }
            else if (startSemester.Equals("Summer"))
            {
                MoveSemesterList.Items.Add(new System.Web.UI.WebControls.ListItem("Summer"));
                MoveSemesterList.Items.Add(new System.Web.UI.WebControls.ListItem("Fall"));
            }
            else // spring
            {
                MoveSemesterList.Items.Add(new System.Web.UI.WebControls.ListItem("Spring"));
                MoveSemesterList.Items.Add(new System.Web.UI.WebControls.ListItem("Summer"));
                MoveSemesterList.Items.Add(new System.Web.UI.WebControls.ListItem("Fall"));
                MoveSemesterList.SelectedIndex = selectedSemesterIndex;
            }
        }
        else
        {
            MoveSemesterList.Items.Add(new System.Web.UI.WebControls.ListItem("Fall"));
            MoveSemesterList.Items.Add(new System.Web.UI.WebControls.ListItem("Spring"));
            MoveSemesterList.Items.Add(new System.Web.UI.WebControls.ListItem("Summer"));
            MoveSemesterList.SelectedIndex = selectedSemesterIndex;
        }
    } //ends ChangeDisplayedSemester()

    /// <summary>
    /// LogButton_Click()
    /// 
    /// Called when user clicks the log button.
    /// </summary>
    /// <param name="sender">object sender (unused, required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void LogButton_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/Advisee/Log.aspx");
    } //end LogButton_Click()

    /// <summary>
    /// NotesButton_Click()
    /// 
    /// Called when user clicks the notes button.
    /// </summary>
    /// <param name="sender">object sender (unused, required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void NotesButton_Click(object sender, EventArgs e)
    {
        //Redirect to Notes Page
        Response.Redirect("~/Advisee/Notes.aspx");
    } //end NotesButton_Click()

    /// <summary>
    /// HelpButton_Click()
    /// 
    /// Called when user clicks the help button.
    /// </summary>
    /// <param name="sender">object sender (unused, required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void HelpButton_Click(object sender, EventArgs e)
    {
        //Redirect to Help Page
        Response.Redirect("~/Advisee/Help.aspx");
    } //end HelpButton_Click()

    /// <summary>
    /// PrintButton_Click()
    /// 
    /// Called when user clicks the Print button.
    /// </summary>
    /// <param name="sender">object sender (unused, required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void PrintButton_Click(object sender, EventArgs e)
    {
        String uid = SharedFunctions.getAdviseeID(Request);
        String path = Server.MapPath("~/PDFs") + "/Schedule" + uid + ".pdf";
        List<Course> courses = populateCourses(uid);
        List<Elective> electives = populateElectives(uid);
        SharedFunctions.generatePDF(uid, path, courses, electives, false);
        Dictionary<String, object> name = StoredProcedures.getAdviseeName(uid);

        try
        {
            WebClient req = new WebClient();
            Response.Clear();
            Response.ClearContent();
            Response.ClearHeaders();
            Response.Buffer = true;
            Response.AddHeader("Content-Disposition", "attachment;filename=" + name["firstName"] + "_" + name["lastName"] + "_" + uid + "_Schedule" + ".pdf");
            byte[] data = req.DownloadData(path);
            Response.BinaryWrite(data);
            Response.End();
        }
        catch (Exception ex)
        {
            //Do nothing on exception
        }
        finally
        {
            File.Delete(path);
        }
    } //end PrintButton_Click()

    /// <summary>
    /// InfoButton_Click()
    /// 
    /// Called when user clicks the advisor info button.
    /// </summary>
    /// <param name="sender">object sender (unused, required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void InfoButton_Click(object sender, EventArgs e)
    {
        //Redirect to Advisor Info Page
        Response.Redirect("~/Advisee/AdvisorInfo.aspx");
    } //end InfoButton_Click()

    /// <summary>
    /// MoveCourseButton_Click()
    /// List View Function
    /// 
    /// Called when user clicks the move course button.
    /// </summary>
    /// <param name="sender">object sender (unused, required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void MoveCourseButton_Click(object sender, EventArgs e)
    {
        //If nothing is selected, then exit (ERROR maybe?)
        if (ListViewSelectedCourse.Text == "")
            return;
        //Mark the selected course to be modified upon save
        searchForCourseToModify();
        //Clear the move year list items so that it can be repopulated
        String startDate = SharedFunctions.getAdviseeStartDate(Session["Advisee_adviseeID"].ToString());
        String startYear = startDate.Substring(startDate.IndexOf(' ') + 1);
        int intStartYear = 0;
        if (!startDate.Equals("Uninitialized"))
             intStartYear = Convert.ToInt32(startYear);
        MoveYearList.Items.Clear();
        //TRANSFER HERE
        MoveYearList.Items.Add(new System.Web.UI.WebControls.ListItem("Transfer Credits"));
        for (int i = intStartYear; i < intStartYear + 10; i++)
        {
            MoveYearList.Items.Add(new System.Web.UI.WebControls.ListItem("" + i));
        }
        //Regenerate the table
        generateListViewTable();
        
    } //end MoveCourseButton_Click()

    /// <summary>
    /// SaveButton_Click()
    /// List View Function
    /// 
    /// Called when user clicks the save button.
    /// </summary>
    /// <param name="sender">object sender (unused, required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void SaveButton_Click(object sender, EventArgs e)
    {

        if (StoredProcedures.addLogEntry(SharedFunctions.getAdviseeID(Request), Session["Advisee_firstName"] + " " + Session["Advisee_lastName"].ToString()) == StoredProcedures.FAILURE)
        {
            MessageBox.Show("Could not add log entry");
        }
        else
        {
            MessageBox.Show("Added entry to Log");
        }
        generateListViewTable();
    } //end SaveButton_Click()

    /// <summary>
    /// getSelectedRadio()
    /// List View Function
    /// 
    /// Called when user selects a course radio button in list view.
    /// </summary>
    /// <param name="sender">object sender (unused, required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void getSelectedRadio(object sender, EventArgs e)
    {
        //Set the SelectedCourse label to the ID of the selected radio button
        RadioButton rb = sender as RadioButton;
        ListViewSelectedCourse.Text = rb.ID;
    } //end getSelectedRadio()

    /// <summary>
    /// chooseElectiveOption()
    /// Graphical View Function
    /// 
    /// Called when user selects an elective option from the drop down.
    /// </summary>
    /// <param name="sender">object sender (required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void chooseElectiveOption(object sender, EventArgs e)
    {
        //Get the relevant info from the dropdown
        DropDownList db = sender as DropDownList;
        String adviseeID = SharedFunctions.getAdviseeID(Request);
        String[] electiveIDAndTerm = db.ID.Split('%');
        //Update the database
        
        //if (StoredProcedures.updateElectiveInSchedule(adviseeID, electiveIDAndTerm[0], "" + db.SelectedItem.Value, electiveIDAndTerm[1]) == StoredProcedures.FAILURE)
        if (StoredProcedures.updateElectiveSelectedCourseInSchedule(adviseeID, electiveIDAndTerm[0], electiveIDAndTerm[2], "" + db.SelectedItem.Value) == StoredProcedures.FAILURE)
        {
            MessageBox.Show("The course you are trying to select for this elective is currently chosen for a different instance of this elective.");
        }
        //Reinitialize the graphical view
        initializeJavaScript();
    } //end chooseElectiveOption()

    /// <summary>
    /// CourseInfoButton_Click()
    /// 
    /// Called when user clicks the course info button for a course.
    /// </summary>
    /// <param name="sender">object sender (required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void CourseInfoButton_Click(object sender, EventArgs e)
    {
        String id = "";
        if (ViewRadio.SelectedIndex == 0) //Graphical View
        {
            //Get the relevant info from the button
            Button bb = sender as Button;
            id = bb.ID.Substring(bb.ID.IndexOf("%") + 1);
        }
        else //List View
        {
            if (ListViewSelectedCourse.Text[0] == 'c')
            {
                id = ListViewSelectedCourse.Text.ToUpper();
            }
            else
            {
                String[] electiveID = ListViewSelectedCourse.Text.Split('%');
                id = electiveID[0].ToUpper();
            }
            
        }
        //Redirect to the CourseInfo page with the appropriate paramaters
        Response.Redirect("~/Advisee/CourseInfo.aspx?cid=" + id);
    } //end CourseInfoButton_Click()

    /// <summary>
    /// LeftButton_Click()
    /// Graphical View Function
    /// 
    /// Called when user clicks the left button.
    /// </summary>
    /// <param name="sender">object sender (unused, required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void LeftButton_Click(object sender, EventArgs e)
    {
        //Get the currently visible year and the start year
        int year = Convert.ToInt32((String)Session["Advisee_yearGV"]);
        String y = SharedFunctions.getAdviseeStartYear(SharedFunctions.getAdviseeID(Request));
        int startYear = Convert.ToInt32(y);
        String startTerm = SharedFunctions.getAdviseeStartSemester(SharedFunctions.getAdviseeID(Request));
        if (startTerm != "Fall")
        {
            startYear--;
        }
        //Decrement year if valid
        if (year >= startYear) year -= 1;
        //Update session variable
        Session["Advisee_yearGV"] = "" + year;
        //Reinitialize the graphical view
        initializeJavaScript();

    } //end LeftButton_Click()

    /// <summary>
    /// RightButton_Click()
    /// Graphical View Function
    /// 
    /// Called when user clicks the right button.
    /// </summary>
    /// <param name="sender">object sender (unused, required by ASP.NET) - web control that called the function</param>
    /// <param name="e">EventArgs e (unused, required by ASP.NET) - other arguments for the function</param>
    protected void RightButton_Click(object sender, EventArgs e)
    {
        //Get the currently visible year and the start year
        int year = Convert.ToInt32((String)Session["Advisee_yearGV"]);
        String y = SharedFunctions.getAdviseeStartYear(SharedFunctions.getAdviseeID(Request));
        int startYear = Convert.ToInt32(y);
        //Increment year if valid
        if (year < (startYear + 10)) year += 1;
        //Update session variable
        Session["Advisee_yearGV"] = "" + year;
        //Reinitialize the graphical view
        initializeJavaScript();

    } //end RightButton_Click()

    /// <summary>
    /// colorViolations
    ///
    /// POSSIBLE Color Values:
    ///  PASS (NO COLORING)
    ///  BORDERLINE (FCB315) //Pale Yellow (60)
    ///  FAIL (AB1E38) //Red (50)
    ///  
    /// preReq/coReq (F15E22) Orange
    /// 
    ///  NULL (NULL GRADE, RIGHT SPOT) (COLORED)    CACBC8 white/cream
    ///  MISSING (NO RECORD OF COURSE) (COLORED)   727075 grey
    ///  WRONG(COURSE RECORD IN DIFFERENT TERM, PREVIOUS OR ) (COLORED) Black 000000 
    ///  
    ///  
    /// Color those methods that are flagged for violation(s)
    /// </summary>
    /// <param name="preCoReqColoring"></param>
    public void colorViolations(Dictionary<String, Object> violations)
    {
        foreach (Control p in GraphicalViewPanel.Controls)
        {
            foreach (Control c in p.Controls)
            {
                if (c is Panel)
                {
                    foreach (Control courseBox in c.Controls)
                    {
                        if (courseBox is Panel)
                        {
                            String courseID = ((Panel)courseBox).ID.Substring(courseBox.ID.IndexOf("$") + 1);
                            if (violations.ContainsKey(courseID))
                            {
                                String courseViolation = (String)((Dictionary<String, Object>)violations[courseID])["violation"];
                                if (courseViolation == "FAIL")
                                {
                                    ((Panel)courseBox).CssClass = "courseFailCSS";
                                }
                                else if (courseViolation == "BORDERLINE")
                                {
                                    ((Panel)courseBox).CssClass = "courseBorderlineCSS";
                                }
                                else if (courseViolation == "preReq" || courseViolation == "coReq")
                                {
                                    ((Panel)courseBox).CssClass = "precoreqViolationsCSS";
                                }
                                else if (courseViolation == "NULL")
                                {
                                    ((Panel)courseBox).CssClass = "courseNullCSS";
                                }
                                else if (courseViolation == "MISSING")
                                {
                                    ((Panel)courseBox).CssClass = "courseMissingCSS";
                                }
                                else if (courseViolation == "WRONG")
                                {
                                    ((Panel)courseBox).CssClass = "courseWrongCSS";
                                }
                                else
                                {
                                    ((Panel)courseBox).CssClass = "courseLabelCSS";
                                }

                            }
                            else
                            {
                                ((Panel)courseBox).CssClass = "courseLabelCSS";
                            }
                        }
                    }
                }
            }//end of foreach Control
        }//end foreach Panel
        return;
    }//end colorViolations()

    /////////////////////////////////////////
    //Web Functions                        //
    // - Require the [WebMethod] tag       //
    // - These are available to JavaScript //
    /////////////////////////////////////////

    /// <summary>
    /// MoveCourse()
    /// Graphical View Function
    /// 
    /// Called when user drops a course on a semester region in GV.
    /// </summary>
    /// <param name="crn">String crn - course ID number, prefaced with the type (c for course, e for elective)</param>
    /// <param name="sem">String sem - the semester region that course was dropped into</param>
    [WebMethod]
    public static void MoveCourse(String crn, String sem)
    {
        //Get the semester region the course was dropped into
        int semester = Convert.ToInt32(sem);
        //Get the currently visible year and the next two
        int y = Convert.ToInt32((String)HttpContext.Current.Session["Advisee_yearGV"]);
        int y1 = y + 1;
        int y2 = y + 2;
        //Get the advisee ID
        String adviseeID = SharedFunctions.getAdviseeID(HttpContext.Current.Request);

        //Determine the term from the semester region and currently visible year
        String term = "";
        switch (semester)
        {
            case 1:
                term = SharedFunctions.convertToTermCode("" + y, "Fall");
                break;
            case 2:
                term = SharedFunctions.convertToTermCode("" + y1, "Spring");
                break;
            case 3:
                term = SharedFunctions.convertToTermCode("" + y1, "Summer");
                break;
            case 4:
                term = SharedFunctions.convertToTermCode("" + y1, "Fall");
                break;
            case 5:
            default:
                term = SharedFunctions.convertToTermCode("" + y2, "Spring");
                break;
        }
        //Ensure term code is accurate length
        int numZeros = 6 - term.Length;
        for (int i = 0; i < numZeros; i++)
        {
            term = "0" + term;
        }

        //Get the course ID (and the selected course ID for electives)
        String courseID = "";
        String selectedCourseID = "";
        //If the dropped box is a course
        if (crn[0] == 'c') //i.e. the id of the box is prefaced with a 'c'
        {
            //Update the database
            courseID = crn.Substring(1);
            if (StoredProcedures.updateCourseInSchedule(adviseeID, courseID, term) == StoredProcedures.FAILURE)
            {
                MessageBox.Show("Could not move the course");
            }
        }
        else //The dropped box is an elective (prefaced with 'e')
        {  
            //The elective ID is before the 's', and the selected course ID is after
            int sloc = crn.IndexOf('s');
            selectedCourseID = crn.Substring(sloc + 1);
            courseID = crn.Substring(1, (sloc - 1));
            //Update the database
            if (StoredProcedures.updateElectiveTermInSchedule(adviseeID, courseID, selectedCourseID, term) == StoredProcedures.FAILURE)
            {
                MessageBox.Show("Could not move the elective");
            }
        }
    } //end MoveCourse()

    /////////////////////
    //Private Functions//
    /////////////////////

    /// <summary>
    /// setUninitView()
    /// 
    /// Sets web controls for uninitialized view to appropriate state.
    /// </summary>
    /// <param name="state">bool state - whether uninitialized view is to be displayed or not</param>
    private void setUninitView(bool state)
    {
        //Main box elements
        UninitBoxText.Visible = state;
        UninitBoxText.Enabled = state;
        //Other buttons - visible if and only if uninitialized view is not visible
        ViewRadio.Enabled = !(state);
        LogButton.Enabled = !(state);
        NotesButton.Enabled = !(state);
        SaveButton.Enabled = !(state);
        PrintButton.Enabled = !(state);
    } //end setUninitView()

    /// <summary>
    /// setGraphicalView()
    /// 
    /// Sets web controls for graphical view to appropriate state.
    /// </summary>
    /// <param name="state">bool state - whether graphical view is to be displayed or not</param>
    private void setGraphicalView(bool state)
    {
        //Main box elements
        GraphicalViewPanel.Visible = state;
        GraphicalViewPanel.Enabled = state;
        LeftButton.Visible = state;
        LeftButton.Enabled = state;
        RightButton.Visible = state;
        RightButton.Enabled = state;
    } //end setGraphicalView()

    /// <summary>
    /// setListView()
    /// 
    /// Sets web controls for list view to appropriate state.
    /// </summary>
    /// <param name="state">bool state - whether list view is to be displayed or not</param>
    private void setListView(bool state)
    {
        //Main box elements
        ListViewPanel.Visible = state;
        ListViewPanel.Enabled = state;
        ListViewOptionsTable.Visible = state;
        ListViewOptionsTable.Enabled = state;
    } //end setListView()

    /// <summary>
    /// populateCourses()
    /// 
    /// Returns a list of courses in the user's schedule.
    /// </summary>
    /// <param name="id">String id - user's ID</param>
    /// <returns>List of courses in the user's schedule</returns>
    private List<Course> populateCourses(String id)
    {
        //Get course info from database
        List<Course> courses = new List<Course>();
        List<Dictionary<String, Object>> results = StoredProcedures.getScheduleCourseInfo(id);
        foreach (Dictionary<String, Object> i in results)
        {
            //Initialize course container objects and add them to list
            Course newCourse = new Course("" + i["courseID"], "" + i["dpt"], "" + i["num"], "" + i["name"], Convert.ToDouble(i["credits"]), "" + i["term"]);
            courses.Add(newCourse);
        }
        //Return fully populated list
        return courses;
    } //end populateCourses()

    /// <summary>
    /// populateElectives()
    /// 
    /// Returns a list of electives in the user's schedule.
    /// </summary>
    /// <param name="id">String id - user's ID</param>
    /// <returns>List of electives in the user's schedule</returns>
    private List<Elective> populateElectives(String id)
    {
        //Get elective info from database
        List<Elective> electives = new List<Elective>();
        List<Dictionary<String, Object>> results = StoredProcedures.getScheduleElectiveInfo(id);
        foreach (Dictionary<String, Object> i in results)
        {
            //Create container objects for course and elective
            Course newCourse = new Course("" + i["selectedCourseID"], "" + i["dpt"], "" + i["num"], "" + i["name"], Convert.ToDouble(i["credits"]), "" + i["term"]);
            Elective newElective = new Elective(Convert.ToInt32(i["electiveID"]), "" + i["electiveName"], newCourse);
            //Get choices for elective and add them as choices the newly created elective
            List<Dictionary<String, Object>> choices = StoredProcedures.getElectiveChoices("" + newElective.getElectiveID());
            foreach (Dictionary<String, Object> j in choices)
            {
                Course newCourseInElective = new Course("" + j["courseID"], "" + j["dpt"], "" + j["num"], "" + j["name"], Convert.ToDouble(j["credits"]), "" + i["term"]);
                newElective.addCourse(newCourseInElective);
            }
            //Add elective to list
            electives.Add(newElective);
        }
        
        //Return fully populated list
        return electives;
    } //end populateElectives()

    /// <summary>
    /// initializeJavaScript()
    /// Graphical View Function
    /// 
    /// Initializes and dynamically creates the pageLoad function for JavaScript and course boxes.
    /// </summary>
    private void initializeJavaScript()
    {
        //Set header of main box to display visible years
        int y = Convert.ToInt32((String)Session["Advisee_yearGV"]);
        int y2 = y + 2;
        HeaderText.Text = y + " - " + y2;

        //Populate lists of courses and electives
        String adviseeID = SharedFunctions.getAdviseeID(Request);
        courseList = populateCourses(adviseeID);
        electiveList = populateElectives(adviseeID);

        //If graphical view has already been initialized before, clear it and start over.
        clearSemesterRegions();

        //Dynamic JavaScript - begin HTML script tag and begin pageLoad function
        JavaScriptPageLoad.Text = "<script type='text/javascript'> function pageLoad() { ";
        //Initialize each part of GV and its associated JavaScript
        initializeSemesterRegions();
        initializeCourseBoxes();
        initializeElectiveBoxes();
        initializeSemesterLabels();
        finalizeSemesterRegions();
        //Dynamic JavaScript - end the pageLoad function and end the HTML tag
        JavaScriptPageLoad.Text += "} </script>";
        //get violations, display and color them
        Dictionary<String, Object> optimizer = SharedFunctions.checkSchedule(adviseeID, courseList, electiveList);
        SharedFunctions.displayViolations(ViolationsLabel, (List<String>)optimizer["violationMessages"]);
        colorViolations(optimizer);

    } //end initializeJavaScript()

    /// <summary>
    /// clearSemesterRegions()
    /// Graphical View Function
    /// 
    /// Resets semester regions and removes all course boxes and labels.
    /// </summary>
    private void clearSemesterRegions()
    {
        //Clear old courses
        SemesterRegion1.Controls.Clear();
        SemesterRegion2.Controls.Clear();
        SemesterRegion3.Controls.Clear();
        SemesterRegion4.Controls.Clear();
        SemesterRegion5.Controls.Clear();
        //Re-add center style
        SemesterRegion1.Controls.Add(new LiteralControl("<center>"));
        SemesterRegion2.Controls.Add(new LiteralControl("<center>"));
        SemesterRegion3.Controls.Add(new LiteralControl("<center>"));
        SemesterRegion4.Controls.Add(new LiteralControl("<center>"));
        SemesterRegion5.Controls.Add(new LiteralControl("<center>"));
        //Re-add labels
        SemesterRegion1.Controls.Add(SemesterLabel1);
        SemesterRegion2.Controls.Add(SemesterLabel2);
        SemesterRegion3.Controls.Add(SemesterLabel3);
        SemesterRegion4.Controls.Add(SemesterLabel4);
        SemesterRegion5.Controls.Add(SemesterLabel5);
        //Re-add Credit Labels
        SemesterRegion1.Controls.Add(SemesterCreditsLabel1);
        SemesterRegion2.Controls.Add(SemesterCreditsLabel2);
        SemesterRegion3.Controls.Add(SemesterCreditsLabel3);
        SemesterRegion4.Controls.Add(SemesterCreditsLabel4);
        SemesterRegion5.Controls.Add(SemesterCreditsLabel5);
        //Re-initialize credits labels
        SemesterCreditsLabel1.Text = "Credits: 0";
        SemesterCreditsLabel2.Text = "Credits: 0";
        SemesterCreditsLabel3.Text = "Credits: 0";
        SemesterCreditsLabel4.Text = "Credits: 0";
        SemesterCreditsLabel5.Text = "Credits: 0";
        //Re-add move labels
        SemesterRegion1.Controls.Add(new LiteralControl("<span id=\"SemMove1\">Moving...</span></center>"));
        SemesterRegion2.Controls.Add(new LiteralControl("<span id=\"SemMove2\">Moving...</span></center>"));
        SemesterRegion3.Controls.Add(new LiteralControl("<span id=\"SemMove3\">Moving...</span></center>"));
        SemesterRegion4.Controls.Add(new LiteralControl("<span id=\"SemMove4\">Moving...</span></center>"));
        SemesterRegion5.Controls.Add(new LiteralControl("<span id=\"SemMove5\">Moving...</span></center>"));
    } //end clearSemesterRegions()

    /// <summary>
    /// finalizeSemesterRegions()
    /// Graphical View Function
    /// 
    /// Calculates and adds padding to semester regions and adds the bottom semester labels.
    /// </summary>
    private void finalizeSemesterRegions()
    {
        //count maximum number of panels in each semester region
        int max = 0;
        int[] counts = { 0, 0, 0, 0, 0 };
        foreach (Control c in SemesterRegion1.Controls)
        {
            if (c is Panel) counts[0] = counts[0] + 1;
        }
        if (counts[0] > max) max = counts[0];
        foreach (Control c in SemesterRegion2.Controls)
        {
            if (c is Panel) counts[1] = counts[1] + 1;
        }
        if (counts[1] > max) max = counts[1];
        foreach (Control c in SemesterRegion3.Controls)
        {
            if (c is Panel) counts[2] = counts[2] + 1;
        }
        if (counts[2] > max) max = counts[2];
        foreach (Control c in SemesterRegion4.Controls)
        {
            if (c is Panel) counts[3] = counts[3] + 1;
        }
        if (counts[3] > max) max = counts[3];
        foreach (Control c in SemesterRegion5.Controls)
        {
            if (c is Panel) counts[4] = counts[4] + 1;
        }
        if (counts[4] > max) max = counts[4];

        //Set maximum height of each semester region appropriately
        max = (max / 4) + 1;
        max = max * 100;
        //Semester Column displayed
        SemesterRegion1.Style["height"] = max + "%";
        SemesterRegion2.Style["height"] = max + "%";
        SemesterRegion3.Style["height"] = max + "%";
        SemesterRegion4.Style["height"] = max + "%";
        SemesterRegion5.Style["height"] = max + "%";

        //Add filler boxes to pad each region
        for (int index = 0; index < 5; index++)
        {
            int limit = max / 100;
            limit = limit * 4;
            limit = limit - 1;
            limit = limit - counts[index];
            for (int i = 0; i < limit; i++)
            {
                Panel p = new Panel();
                p.CssClass = "courseFillerCSS";
                switch (index)
                {
                    case 0:
                        SemesterRegion1.Controls.Add(p);
                        SemesterRegion1.Controls.Add(new LiteralControl("<br />"));
                        break;
                    case 1:
                        SemesterRegion2.Controls.Add(p);
                        SemesterRegion2.Controls.Add(new LiteralControl("<br />"));
                        break;
                    case 2:
                        SemesterRegion3.Controls.Add(p);
                        SemesterRegion3.Controls.Add(new LiteralControl("<br />"));
                        break;
                    case 3:
                        SemesterRegion4.Controls.Add(p);
                        SemesterRegion4.Controls.Add(new LiteralControl("<br />"));
                        break;
                    case 4:
                    default:
                        SemesterRegion5.Controls.Add(p);
                        SemesterRegion5.Controls.Add(new LiteralControl("<br />"));
                        break;
                }
            }
        }

        //Add center style
        SemesterRegion1.Controls.Add(new LiteralControl("<br /><center>"));
        SemesterRegion2.Controls.Add(new LiteralControl("<br /><center>"));
        SemesterRegion3.Controls.Add(new LiteralControl("<br /><center>"));
        SemesterRegion4.Controls.Add(new LiteralControl("<br /><center>"));
        SemesterRegion5.Controls.Add(new LiteralControl("<br /><center>"));

        //Add labels with following properties:
        //Enabled="false" BorderStyle="None" Width="90%" CssClass="labelCSS"
        for (int i = 1; i <= 5; i++)
        {
            TextBox slc = new TextBox();
            slc.Enabled = false;
            slc.BorderStyle = BorderStyle.None;
            slc.Width = new Unit("90%");
            slc.CssClass = "labelCSS";
            switch (i)
            {
                case 1:
                    slc.Text = SemesterLabel1.Text;
                    SemesterRegion1.Controls.Add(slc);
                    break;
                case 2:
                    slc.Text = SemesterLabel2.Text;
                    SemesterRegion2.Controls.Add(slc);
                    break;
                case 3:
                    slc.Text = SemesterLabel3.Text;
                    SemesterRegion3.Controls.Add(slc);
                    break;
                case 4:
                    slc.Text = SemesterLabel4.Text;
                    SemesterRegion4.Controls.Add(slc);
                    break;
                case 5:
                default:
                    slc.Text = SemesterLabel5.Text;
                    SemesterRegion5.Controls.Add(slc);
                    break;
            }

        }

        //End center styling
        SemesterRegion1.Controls.Add(new LiteralControl("</center>"));
        SemesterRegion2.Controls.Add(new LiteralControl("</center>"));
        SemesterRegion3.Controls.Add(new LiteralControl("</center>"));
        SemesterRegion4.Controls.Add(new LiteralControl("</center>"));
        SemesterRegion5.Controls.Add(new LiteralControl("</center>"));
    } //end finalizeSemesterRegions()

    /// <summary>
    /// initializeCourseBoxes()
    /// Graphical View Function
    /// 
    /// Dynamically creates course boxes and places them in the appropriate semester containers.
    /// </summary>
    private void initializeCourseBoxes()
    {
        //Get currently visible year
        int y = Convert.ToInt32((String)Session["Advisee_yearGV"]);
        foreach (Course c in courseList)
        {
            //Get relevant course info
            String term = c.getSemester();
            int cyear = c.getYear();
            String deptNum = c.getDpt() + c.getNum();
            String termCode = SharedFunctions.convertToTermCode((String)Session["Advisee_yearGV"], term);
            //If current course is not within currently visible years, then skip over it
            if ((cyear < y) || (cyear > (y + 2))) continue;
            
            //Determine place of course on schedule
            if (cyear == y)
            {
                if (!term.Equals("Fall")) continue; //Only fall of first year is visible
                createCourseBox(c.getCourseID(), deptNum, c.getName(), c.getCredits(), 1, termCode);
                UpdateSemesterCreditsLabel(1, c.getCredits());
            }
            else if (cyear == (y + 1))
            {
                if (term.Equals("Spring"))
                {
                    createCourseBox(c.getCourseID(), deptNum, c.getName(), c.getCredits(), 2, termCode); //Spring of second visible year
                    UpdateSemesterCreditsLabel(2, c.getCredits());
                }
                else if (term.Equals("Summer"))
                {
                    createCourseBox(c.getCourseID(), deptNum, c.getName(), c.getCredits(), 3, termCode); //Summer
                    UpdateSemesterCreditsLabel(3, c.getCredits());
                }
                else
                {
                    createCourseBox(c.getCourseID(), deptNum, c.getName(), c.getCredits(), 4, termCode); //Fall
                    UpdateSemesterCreditsLabel(4, c.getCredits());
                }
            }
            else //if (cyear == (y + 2))
            {
                if (!term.Equals("Spring")) continue; //Only spring of third year is visible
                createCourseBox(c.getCourseID(), deptNum, c.getName(), c.getCredits(), 5, termCode);
                UpdateSemesterCreditsLabel(5, c.getCredits());
            }
        }
    } //end initializeCourseBoxes()

    /// <summary>
    /// initializeElectiveBoxes()
    /// Graphical View Function
    /// 
    /// Dynamically creates elective boxes and places them in the appropriate semester containers.
    /// </summary>
    private void initializeElectiveBoxes()
    {
        //Get currently visible year
        int y = Convert.ToInt32((String)Session["Advisee_yearGV"]);
        foreach (Elective e in electiveList)
        {
            //Get relevant elective info
            String term = e.getSemester();
            int eyear = e.getYear();

            //If current elective is not within currently visible years, then skip over it
            if ((eyear < y) || (eyear > (y + 2))) continue;

            //Determine place of elective on schedule
            if (eyear == y)
            {
                if (!term.Equals("Fall")) continue; //Only fall of first year is visible
                createElectiveBox(e.getElectiveID(), e.getElectiveName(), e.getTerm(), e.getCredits(), e.getCourses(), e.getSelectedCourseID(), 1);
                UpdateSemesterCreditsLabel(1, e.getCredits());
            }
            else if (eyear == (y + 1))
            {
                if (term.Equals("Spring"))
                {
                    createElectiveBox(e.getElectiveID(), e.getElectiveName(), e.getTerm(), e.getCredits(), e.getCourses(), e.getSelectedCourseID(), 2); //Spring of second visible year
                    UpdateSemesterCreditsLabel(2, e.getCredits());
                }
                else if (term.Equals("Summer"))
                {
                    createElectiveBox(e.getElectiveID(), e.getElectiveName(), e.getTerm(), e.getCredits(), e.getCourses(), e.getSelectedCourseID(), 3); //Summer
                    UpdateSemesterCreditsLabel(3, e.getCredits());
                }
                else
                {
                    createElectiveBox(e.getElectiveID(), e.getElectiveName(), e.getTerm(), e.getCredits(), e.getCourses(), e.getSelectedCourseID(), 4); //Fall
                    UpdateSemesterCreditsLabel(4, e.getCredits());
                }
            }
            else //if (eyear == (y + 2))
            {
                if (!term.Equals("Spring")) continue; //Only spring of third year is visible
                createElectiveBox(e.getElectiveID(), e.getElectiveName(), e.getTerm(), e.getCredits(), e.getCourses(), e.getSelectedCourseID(), 5);
                UpdateSemesterCreditsLabel(5, e.getCredits());
            }

        }
    } //end initializeElectiveBoxes()

    /// <summary>
    /// initializeSemesterLabels()
    /// Graphical View Function
    /// 
    /// Set semester labels to display the correct semester information.
    /// </summary>
    private void initializeSemesterLabels()
    {
        //Get currently visible years
        int startYear = Convert.ToInt32(SharedFunctions.getAdviseeStartYear(SharedFunctions.getAdviseeID(Request)));
        String startTerm = SharedFunctions.getAdviseeStartSemester(SharedFunctions.getAdviseeID(Request));
        if(startTerm != "Fall"){
            startYear--;
        }

        int y = Convert.ToInt32((String)Session["Advisee_yearGV"]);
        int y1 = y + 1;
        int y2 = y + 2;
        //Initialize labels
        if (y < startYear)
        {
            SemesterLabel1.Text = "Transfer Credits";
            SemesterLabel2.Text = "Transfer Credits";
            SemesterLabel3.Text = "Transfer Credits";
        }
        else // at least start year
        {
            SemesterLabel1.Text = "Fall " + y;
            SemesterLabel2.Text = "Spring " + y1;
            SemesterLabel3.Text = "Summer " + y1;
        }
        SemesterLabel4.Text = "Fall " + y1;
        SemesterLabel5.Text = "Spring " + y2;
    } //end initializeSemesterLabels()

    /// <summary>
    /// initializeSemesterRegions()
    /// Graphical View Function
    /// 
    /// Create JavaScript code for initializing semester regions as drop targets.
    /// </summary>
    private void initializeSemesterRegions()
    {
        for (int i = 1; i <= 5; i++)
        {
            //Dynamic JavaScript - create code for each drop target
            JavaScriptPageLoad.Text += "var target" + i + " = new AdviseUP.UI.SemesterRegion($get('MainBox_SemesterRegion" + i + "'), '" + i + "'); ";
            JavaScriptPageLoad.Text += "target" + i + ".initialize(); ";
        }
    } //end initializeSemesterRegions()

    /// <summary>
    /// createCourseBox()
    /// Graphical View Function
    /// 
    /// Create an individual course box with ASP.NET web controls.
    /// Also, create JavaScript code for initializing the course box as a drag source.
    /// </summary>
    /// <param name="courseID">int courseID - the unique course ID in the database</param>
    /// <param name="deptNum">String deptNum - the department and number of the course (e.g. CS203)</param>
    /// <param name="courseName">String courseName - the name of the course</param>
    /// <param name="credits">double credits - the number of credits for the course</param>
    /// <param name="regionNumber">int regionNumber - the semester region that the course is currently located (1 through 5)</param>
    /// <param name="term">String term - the term or column this course will be in</param>
    private void createCourseBox(String courseID, String deptNum, String courseName, double credits, int regionNumber, String term)
    {
        //Create each container and control, placing appropriate controls in the right container
        //Outer Panel (Container, White, Non-Draggable)
        Panel p = new Panel();
        p.CssClass = "courseCSS";
        //Inner Panel (Container, Blue, Draggable, inside Outer Panel)
        Panel cb = new Panel();
        //cb is the course box with the background-color we need to change
        cb.ID = "CourseBoxc$" + courseID;
        cb.CssClass = "courseLabelCSS";
        //Course Name Text (inside Inner Panel)
        Literal lit = new Literal();
        lit.Text = "<span style=\"font-size:12px;\">" + deptNum + " (" + credits + ")" + "</span><br />";
        lit.Text += "<span>" + courseName + "</span>";
        //Course Info Button (inside Outer Panel)
        Button bb1 = new Button();
        bb1.Text = "Course Info";
        bb1.ID = "InfoButton%C" + courseID;
        bb1.Click += new EventHandler(CourseInfoButton_Click);
        //Add controls to Inner Panel
        cb.Controls.Add(lit);
        //Add controls to Outer Panel
        p.Controls.Add(cb);
        p.Controls.Add(new LiteralControl("<center>"));
        p.Controls.Add(bb1);
        p.Controls.Add(new LiteralControl("</center>"));

        //Add course to correct semester region
        switch (regionNumber)
        {
            case 1:
                SemesterRegion1.Controls.Add(p);
                SemesterRegion1.Controls.Add(new LiteralControl("<br /><br />"));
                break;
            case 2:
                SemesterRegion2.Controls.Add(p);
                SemesterRegion2.Controls.Add(new LiteralControl("<br /><br />"));
                break;
            case 3:
                SemesterRegion3.Controls.Add(p);
                SemesterRegion3.Controls.Add(new LiteralControl("<br /><br />"));
                break;
            case 4:
                SemesterRegion4.Controls.Add(p);
                SemesterRegion4.Controls.Add(new LiteralControl("<br /><br />"));
                break;
            case 5:
            default:
                SemesterRegion5.Controls.Add(p);
                SemesterRegion5.Controls.Add(new LiteralControl("<br /><br />"));
                break;
        }

        //Dynamic JavaScript - create code for drag source
        JavaScriptPageLoad.Text += "var sourceC" + courseID + " = new AdviseUP.UI.CourseBox($get('MainBox_CourseBoxc$" + courseID + "'), 'c" + courseID + "'); ";
        JavaScriptPageLoad.Text += "sourceC" + courseID + ".initialize();";
    } //end createCourseBox()

    /// <summary>
    /// createElectiveBox()
    /// Graphical View Function
    /// 
    /// Create an individual elective box with ASP.NET web controls.
    /// Also, create JavaScript code for initializing the elective box as a drag source.
    /// </summary>
    /// <param name="electiveID">int electiveID - the unique database ID of the elective</param>
    /// <param name="electiveName">String electiveName - the name of the elective</param>
    /// <param name="term">String term - the current term of the elective</param>
    /// <param name="credits">double credits - the number of credits that the selected course is worth</param>
    /// <param name="choiceList">Dictionary(int, Course) choiceList - the list of elective choices</param>
    /// <param name="selectedCourseID">int selectedCourseID - the unique database ID of the currently selected course</param>
    /// <param name="regionNumber">int regionNumber - the semester region that the course is currently located (1 through 5)</param>
    private void createElectiveBox(int electiveID, String electiveName, String term, double credits, Dictionary<String, Course> choiceList, String selectedCourseID, int regionNumber)
    {
        //Create each container and control, placing appropriate controls in the right container
        //Outer Panel (Container, White, Non-Draggable)
        Panel p = new Panel();
        p.CssClass = "electiveCSS";
        //Inner Panel (Container, Blue, Draggable, inside Outer Panel)
        Panel eb = new Panel();
        eb.ID = "CourseBoxe" + electiveID + "$" + selectedCourseID; 
        eb.CssClass = "courseLabelCSS";
        //Elective Name Text (inside Inner Panel)
        Literal lit = new Literal();
        lit.Text = "<span style=\"font-size:12px;\">Elective: " + electiveName + " (" + credits + ")" + "</span><br />";
        //Elective Choices Dropdown (inside Outer Panel)
        DropDownList db = new DropDownList();
        db.ID = electiveID + "%" + term + "%" + selectedCourseID;
        db.Width = new Unit("90%");
        db.AutoPostBack = true;
        db.SelectedIndexChanged += new EventHandler(chooseElectiveOption);
        db.Items.Add(new System.Web.UI.WebControls.ListItem("Choose Option", "" + -1));
        String selectedName = "";
        foreach (String i in choiceList.Keys)
        {
            Course c = choiceList[i];
            String name = c.getDpt() + c.getNum() + ": " + c.getName();
            db.Items.Add(new System.Web.UI.WebControls.ListItem(name, "" + i));
            if (selectedCourseID == i)
            {
                selectedName = name;
            }
        }
        //Selected Course Name Text (inside Inner Panel)
        lit.Text += "<span>" + selectedName + "</span>";
        //Elective Info Button (inside Outer Panel)
        Button bb1 = new Button();
        bb1.Text = "Elective Info";
        bb1.ID = "InfoButton" + selectedCourseID + "%E" + electiveID;
        bb1.Click += new EventHandler(CourseInfoButton_Click);
        //Add controls to Inner Panel
        eb.Controls.Add(lit);
        //Add controls to Outer Panel
        p.Controls.Add(eb);
        p.Controls.Add(db);
        p.Controls.Add(new LiteralControl("<br /><center>"));
        p.Controls.Add(bb1);
        p.Controls.Add(new LiteralControl("</center>"));

        //Add elective to correct semester region
        switch (regionNumber)
        {
            case 1:
                SemesterRegion1.Controls.Add(p);
                SemesterRegion1.Controls.Add(new LiteralControl("<br />"));
                break;
            case 2:
                SemesterRegion2.Controls.Add(p);
                SemesterRegion2.Controls.Add(new LiteralControl("<br />"));
                break;
            case 3:
                SemesterRegion3.Controls.Add(p);
                SemesterRegion3.Controls.Add(new LiteralControl("<br />"));
                break;
            case 4:
                SemesterRegion4.Controls.Add(p);
                SemesterRegion4.Controls.Add(new LiteralControl("<br />"));
                break;
            case 5:
            default:
                SemesterRegion5.Controls.Add(p);
                SemesterRegion5.Controls.Add(new LiteralControl("<br />"));
                break;
        }
        

        //Dynamic JavaScript - create code for drag source
        JavaScriptPageLoad.Text += "var sourceE" + electiveID + selectedCourseID + " = new AdviseUP.UI.CourseBox($get('MainBox_CourseBoxe" + electiveID + "$" + selectedCourseID + "'), 'e" + electiveID + "s" + selectedCourseID + "'); ";
        JavaScriptPageLoad.Text += "sourceE" + electiveID + selectedCourseID + ".initialize();";
    } //end createElectiveBox()

    /// <summary>
    /// UpdateSemesterCreditsLabel()
    /// Graphical View Function
    /// 
    /// Updates the label listing how many credits being taken in a semester.
    /// </summary>
    /// <param name="sem">int sem - the semester to update</param>
    /// <param name="credits">int creditsToAdd - the number of credits to add to the running total</param>
    private void UpdateSemesterCreditsLabel(int sem, double creditsToAdd)
    {
        int space = 0;
        double creditsSoFar = 0;
        switch (sem)
        {
            case 1:
                space = SemesterCreditsLabel1.Text.IndexOf(' ');
                creditsSoFar = Convert.ToDouble(SemesterCreditsLabel1.Text.Substring(space + 1));
                creditsSoFar += creditsToAdd;
                SemesterCreditsLabel1.Text = "Credits: " + creditsSoFar;
                break;
            case 2:
                space = SemesterCreditsLabel2.Text.IndexOf(' ');
                creditsSoFar = Convert.ToDouble(SemesterCreditsLabel2.Text.Substring(space + 1));
                creditsSoFar += creditsToAdd;
                SemesterCreditsLabel2.Text = "Credits: " + creditsSoFar;
                break;
            case 3:
                space = SemesterCreditsLabel3.Text.IndexOf(' ');
                creditsSoFar = Convert.ToDouble(SemesterCreditsLabel3.Text.Substring(space + 1));
                creditsSoFar += creditsToAdd;
                SemesterCreditsLabel3.Text = "Credits: " + creditsSoFar;
                break;
            case 4:
                space = SemesterCreditsLabel4.Text.IndexOf(' ');
                creditsSoFar = Convert.ToDouble(SemesterCreditsLabel4.Text.Substring(space + 1));
                creditsSoFar += creditsToAdd;
                SemesterCreditsLabel4.Text = "Credits: " + creditsSoFar;
                break;
            case 5: default:
                space = SemesterCreditsLabel5.Text.IndexOf(' ');
                creditsSoFar = Convert.ToDouble(SemesterCreditsLabel5.Text.Substring(space + 1));
                creditsSoFar += creditsToAdd;
                SemesterCreditsLabel5.Text = "Credits: " + creditsSoFar;
                break;
        }
    } //end UpdateSemesterCreditsLabel()

    /// <summary>
    /// searchForCourseToModify()
    /// List View Function
    /// 
    /// Moves a course or elective in list view.
    /// </summary>
    private void searchForCourseToModify()
    {
        //Find the course/elective
        List<Course> courses = populateCourses(Session["Advisee_adviseeID"].ToString());
        List<Elective> electives = populateElectives(Session["Advisee_adviseeID"].ToString());

        String startYear = SharedFunctions.getAdviseeStartYear(Session["Advisee_adviseeID"].ToString());
        String startSemester = SharedFunctions.getAdviseeStartSemester(Session["Advisee_adviseeID"].ToString());

        String termCode = "ERROR";
        if(MoveYearList.SelectedItem.Text.Equals("Transfer Credits"))
        {
            if(startSemester.Equals("Fall"))
            {
                termCode = SharedFunctions.convertToTermCode(startYear, "Summer");
            }
            else if (startSemester.Equals("Summer"))
            {
                termCode = SharedFunctions.convertToTermCode(startYear, "Spring");
            }
            else
            {
                String moveYear = (Convert.ToInt32(startYear) - 1).ToString();
                termCode = SharedFunctions.convertToTermCode(moveYear, "Fall");
            }
        }
        else
            termCode = SharedFunctions.convertToTermCode(MoveYearList.SelectedItem.Text, MoveSemesterList.SelectedItem.Text);
        if (ListViewSelectedCourse.Text.Substring(0, 1).Equals("c"))
        {
            String courseID = ListViewSelectedCourse.Text.Substring(1);
            foreach (Course c in courses)
            {
                if (c.getCourseID() == courseID)
                {
                    //Update the course's term code
                    if (StoredProcedures.updateCourseInSchedule(Session["Advisee_adviseeID"].ToString(), courseID.ToString(), termCode) == StoredProcedures.FAILURE)
                    {
                        MessageBox.Show("Could not move the course");
                    }
                    return;
                }
            }
        }
        else
        {
            //split the text into the electiveID and selectedCourseID 
            String electiveAndCourseID = ListViewSelectedCourse.Text;
            int sloc = electiveAndCourseID.IndexOf("%");
            String selectedCourseID = electiveAndCourseID.Substring(sloc + 1);
            int electiveID = Convert.ToInt32(electiveAndCourseID.Substring(1, sloc - 1));
            foreach (Elective e in electives)
            {
                if (e.getElectiveID() == electiveID && e.getSelectedCourseID() == selectedCourseID)
                {
                    //Update the elective's term code
                    if (StoredProcedures.updateElectiveTermInSchedule(Session["Advisee_adviseeID"].ToString(),
                        e.getElectiveID().ToString(), e.getSelectedCourseID().ToString(), termCode) == StoredProcedures.FAILURE)
                    {
                        MessageBox.Show("Could not move the elective");
                    }
                    return;
                }
            }
        }
        
    } //end searchForCourseToModify()

    /// <summary>
    /// generateListViewTable()
    /// List View Function
    /// 
    /// Dynamically creates the ListViewTable and populates it with radio buttons for each course and elective.
    /// CLIAFD - improve these comments... do as good as you can... i know it's hard for you
    /// </summary>
    private void generateListViewTable()
    {
        //Clear ListViewTable if already generated
        
        ListViewCourseTable.Controls.Clear();
        List<Course> courses = populateCourses(Session["Advisee_adviseeID"].ToString());
        List<Elective> electives = populateElectives(Session["Advisee_adviseeID"].ToString());
        List<Course> electivesAndCourses = new List<Course>();
        //Get the start year, exiting if user is uninitialized
        String startYear = SharedFunctions.getAdviseeStartYear(SharedFunctions.getAdviseeID(Request));
        if (startYear.Equals("Uninitialized"))
            return;
        SharedFunctions.displayViolations(ViolationsLabel, (List<String>)SharedFunctions.checkSchedule(Session["Advisee_adviseeID"].ToString(), courses, electives)["violationMessages"]);
        int intStartYear = Convert.ToInt32(startYear);
        foreach (Course c in courses)
        {
            electivesAndCourses.Add(c);
        }
        foreach (Elective e in electives)
        {
            electivesAndCourses.Add(e);
        }
        int largestStartDate = 0;
        foreach (Course c in electivesAndCourses)
        {
            int term = Convert.ToInt32(c.getYear());
            if (term > largestStartDate)
            {
                largestStartDate = term;
            }
        }
        int numberOfYears = (largestStartDate - intStartYear) + 1;
        String startSemester = SharedFunctions.getAdviseeStartSemester(SharedFunctions.getAdviseeID(Request));
        String starTerm = SharedFunctions.convertToTermCode(startYear, startSemester);
        if (startSemester.Equals("Fall"))
        {
            intStartYear++;
        }

        //create Transfer Credits Cell
        TableRow first = new TableRow();
        TableCell transfer = new TableCell();
        transfer.Width = new Unit("33%");
        transfer.CssClass = "listCell";
        transfer.Controls.Add(new LiteralControl("Transfer Credits<br />"));
        double creds = 0;

        foreach (Course course in electivesAndCourses)
        {

            //if start semester is Fall
            if (Convert.ToInt32(course.getTerm()) < Convert.ToInt32(starTerm))
            {
                creds += course.getCredits();
                //Create a radio button
                RadioButton radio = new RadioButton();
                if (course is Elective)
                {
                    Elective elective = course as Elective;
                    radio.Text = "Elective: " + course.getDpt() + course.getNum() + " " + course.getName() + " (" + course.getCredits() + ")";
                    radio.ID = "e" + elective.getElectiveID() + "%" + elective.getSelectedCourseID();
                }
                else
                {
                    radio.Text = course.getDpt() + course.getNum() + " " + course.getName() + " (" + course.getCredits() + ")";
                    radio.ID = "c" + course.getCourseID();
                }
                radio.GroupName = "Schedule";
                radio.AutoPostBack = true;
                //Adds an event handling function to be called when the radio button is selected
                radio.CheckedChanged += new EventHandler(getSelectedRadio);
                transfer.Controls.Add(radio);
                transfer.Controls.Add(new LiteralControl("<br />"));
            }
        }
        transfer.Controls.Add(new LiteralControl("Credits: " + creds));
        first.Controls.Add(transfer);
        ListViewCourseTable.Controls.Add(first);

        //Iterate for as many years as was just determined
        for (int i = intStartYear; i < intStartYear + numberOfYears; i++)
        {
            //Initialize new row and container lists
            //Put all the fall, spring, and summer courses in their place appropriately
            TableRow r = new TableRow();
            List<Course> fallCourses = new List<Course>();
            List<Course> springCourses = new List<Course>();
            List<Course> summerCourses = new List<Course>();

            for (int j = 0; j < 3; j++)
            {
                int year = i;
                //Create new cells for each semester
                TableCell c = new TableCell();
                c.Width = new Unit("33%");
                c.CssClass = "listCell";
                String semesterName = "";
                if (j == 0)
                {
                    semesterName = "Fall";
                    year--;
                }
                else if (j == 1)
                {
                    semesterName = "Spring";
                }
                else
                {
                    semesterName = "Summer";
                }
                c.Controls.Add(new LiteralControl(semesterName + " " + year + "<br />"));

                double credits = 0;
                foreach (Course course in electivesAndCourses)
                {
                    if (!semesterName.Equals("Fall"))
                    {
                        if (course.getYear() == i && course.getSemester().Equals(semesterName))
                        {
                            credits += course.getCredits();
                            //Create a radio button
                            RadioButton rb = new RadioButton();
                            if (course is Elective)
                            {
                                Elective elective = course as Elective;
                                rb.Text = "Elective: " + course.getDpt() + course.getNum() + " " + course.getName() + " (" + course.getCredits() + ")";
                                rb.ID = "e" + elective.getElectiveID() + "%" + elective.getSelectedCourseID();
                            }
                            else
                            {
                                rb.Text = course.getDpt() + course.getNum() + " " + course.getName() + " (" + course.getCredits() + ")";
                                rb.ID = "c" + course.getCourseID();
                            }
                            rb.GroupName = "Schedule";
                            rb.AutoPostBack = true;
                            //Adds an event handling function to be called when the radio button is selected
                            rb.CheckedChanged += new EventHandler(getSelectedRadio);
                            c.Controls.Add(rb);
                            c.Controls.Add(new LiteralControl("<br />"));
                        }
                    }
                    else
                    {
                        if (course.getYear() == i - 1 && course.getSemester().Equals(semesterName))
                        {
                            credits += course.getCredits();
                            //Create a radio button
                            RadioButton rb = new RadioButton();
                            if (course is Elective)
                            {
                                Elective elective = course as Elective;
                                rb.Text = "Elective: " + course.getDpt() + course.getNum() + " " + course.getName() + " (" + course.getCredits() + ")";
                                //rb.ID = "e" + elective.getElectiveID(); Original version of ID (what they're expecting us to do)
                                rb.ID = "e" + elective.getElectiveID() + "%" + elective.getSelectedCourseID();
                            }
                            else
                            {
                                rb.Text = course.getDpt() + course.getNum() + " " + course.getName() + " (" + course.getCredits() + ")";
                                rb.ID = "c" + course.getCourseID();
                            }
                            rb.GroupName = "Schedule";
                            rb.AutoPostBack = true;
                            //Adds an event handling function to be called when the radio button is selected
                            rb.CheckedChanged += new EventHandler(getSelectedRadio);
                            c.Controls.Add(rb);
                            c.Controls.Add(new LiteralControl("<br />"));
                        }
                    }
                }
                c.Controls.Add(new LiteralControl("Credits: " + credits));
                r.Controls.Add(c);
            }
            ListViewCourseTable.Controls.Add(r);
        }
    } //end generateListViewTable()
}